<?php
namespace tp5_lib\wxpay\utility;

require_once __DIR__ . "/../lib/WxPay.Data.php";
require_once __DIR__ . "/../lib/WxPay.Config.php";
require_once __DIR__ . "/../lib/WxPay.Api.php";
require_once __DIR__ . "/../lib/WxPay.Exception.php";
require_once __DIR__ . "/../lib/WxPay.Notify.php";

use tp5_lib\common\logic\Logic;
use tp5_lib\wxpay\lib\WxPayApi;
use tp5_lib\wxpay\lib\WxPayUnifiedOrder;
use tp5_lib\wxpay\lib\WxPayConfig;
use tp5_lib\wxpay\lib\Notify;
use tp5_lib\account\extension\PaymentMethod;

class WxPay extends Logic implements PaymentMethod
{
    /**
     * 预创建
     * @param string $no 订单编号
     * @param float $amount 订单金额
     * @param string $title 标题
     * @param string $content 内容
     */
    public function precreate($no,$amount,$title,$content="")
    {
        $input = new WxPayUnifiedOrder();
        $input->SetBody("test");
        $input->SetAttach("test");
        $input->SetOut_trade_no($no);
        $input->SetTotal_fee(intval($amount * 100));//微信支付的金额是以分为单位的
        $input->SetGoods_tag("test");
        $input->SetNotify_url("http://paysdk.weixin.qq.com/notify.php");
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id("123456789");

        $config = new WxPayConfig();

        $result = WxPayApi::unifiedOrder($config, $input);
        
        require_once '../extend/phpqrcode.php';
        header("Content-type: image/png");
        \QRcode::png($result["code_url"]);
        exit;
    }
    public function notify()
    {
        $config = new WxPayConfig();
        $notify = new Notify();
        $notify->config = $config;
		$msg = "OK";
		$result = WxpayApi::notify($config, array($notify, 'NotifyCallBack'), $msg);
		if($result == false){
			$notify->SetReturn_code("FAIL");
			$notify->SetReturn_msg($msg);
			$notify->ReplyNotify(false);
			return;
		} else {
			$notify->SetReturn_code("SUCCESS");
			$notify->SetReturn_msg("OK");
		}
		$notify->ReplyNotify(false);
    }
}
